import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import '../models/question.dart';
import '../services/database_service.dart';
import '../utils/word_export_util.dart';
import '../widgets/math_formula_widget.dart';
import 'dart:developer' as developer;
import 'dart:io';

class QuestionPracticeScreen extends StatefulWidget {
  final String questionType;
  
  const QuestionPracticeScreen({super.key, required this.questionType});

  @override
  State<QuestionPracticeScreen> createState() => _QuestionPracticeScreenState();
}

class _QuestionPracticeScreenState extends State<QuestionPracticeScreen> {
  int _currentIndex = 0;
  bool _showAnswer = false;
  bool _isLoading = true;
  String? _errorMessage;
  List<Question> _questions = [];
  String? _selectedOption; // 用户选择的选项
  bool? _isCorrect; // 用户选择是否正确
  final DatabaseService _databaseService = DatabaseService();
  
  // 创建一个全局key来访问Scaffold
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  
  // 记录每道题的答题情况
  Map<int, String> _userAnswers = {}; // 题目索引 -> 用户选择的选项
  Map<int, bool> _correctStatus = {}; // 题目索引 -> 是否正确
  
  @override
  void initState() {
    super.initState();
    _loadQuestions();
  }
  
  @override
  void dispose() {
    super.dispose();
  }
  

  
  Future<void> _loadQuestions() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });
      
      // 确保数据库已初始化
      await _databaseService.init();
      
      // 根据题目类型获取所有题目
      List<Question> questions = await _databaseService.questionRepository.getAllQuestions()
          .then((allQuestions) => allQuestions.where((q) => q.type == widget.questionType).toList());
      
      // 确保返回的是Question对象列表
      setState(() {
        _questions = questions;
        _isLoading = false;
        // 重置当前索引，防止越界
        _currentIndex = _questions.isEmpty ? 0 : (_currentIndex >= _questions.length ? 0 : _currentIndex);
      });
      
      // 如果没有题目，记录日志
      if (_questions.isEmpty) {
        developer.log('没有找到符合条件的${questionTypeTitle}类型的题目');
      } else {
        developer.log('成功加载${_questions.length}道${questionTypeTitle}类型的题目');
      }
    } catch (e) {
      developer.log('加载题目失败: $e', error: e);
      setState(() {
        _isLoading = false;
        _errorMessage = '加载题目失败: $e';
      });
    }
  }
  
  String get questionTypeTitle {
    switch (widget.questionType) {
      case 'politics':
        return '时政题目';
      case 'common_sense':
        return '常识判断';
      case 'verbal_comprehension':
        return '言语理解与表达';
      case 'quantitative_relation':
        return '数量关系';
      case 'logical_reasoning':
        return '判断推理';
      case 'data_analysis':
        return '资料分析';
      default:
        return '题目';
    }
  }
  
  void _toggleAnswer() {
    // 只在已选择选项时才能切换答案显示
    if (_selectedOption != null) {
      setState(() {
        _showAnswer = !_showAnswer;
      });
    }
  }
  
  void _nextQuestion() {
    if (_questions.isEmpty) return;
    setState(() {
      _currentIndex = (_currentIndex + 1) % _questions.length;
      // 检查是否已经回答过这道题
      if (_userAnswers.containsKey(_currentIndex)) {
        _selectedOption = _userAnswers[_currentIndex];
        _isCorrect = _correctStatus[_currentIndex];
        _showAnswer = true; // 已回答过的题目直接显示答案
      } else {
        _showAnswer = false;
        _selectedOption = null;
        _isCorrect = null;
      }
    });
    // 记录用户切换题目的行为
    developer.log('用户切换到下一题: ${_currentIndex + 1}/${_questions.length}');
  }
  
  void _previousQuestion() {
    if (_questions.isEmpty) return;
    setState(() {
      _currentIndex = (_currentIndex - 1 + _questions.length) % _questions.length;
      // 检查是否已经回答过这道题
      if (_userAnswers.containsKey(_currentIndex)) {
        _selectedOption = _userAnswers[_currentIndex];
        _isCorrect = _correctStatus[_currentIndex];
        _showAnswer = true; // 已回答过的题目直接显示答案
      } else {
        _showAnswer = false;
        _selectedOption = null;
        _isCorrect = null;
      }
    });
    // 记录用户切换题目的行为
    developer.log('用户切换到上一题: ${_currentIndex + 1}/${_questions.length}');
  }
  
  // 选择选项
  void _selectOption(String option) {
    if (_selectedOption != null || _showAnswer) return; // 已经选择或显示答案时不允许再选
    
    final bool isCorrect = option == _questions[_currentIndex].correctAnswer;
    
    setState(() {
      _selectedOption = option;
      _isCorrect = isCorrect;
      _showAnswer = true; // 选择选项后直接显示答案和解析
      
      // 记录答题情况
      _userAnswers[_currentIndex] = option;
      _correctStatus[_currentIndex] = isCorrect;
    });
  }
  
  // 构建筛选面板

  
  // 显示答题卡抽屉
  void _showAnswerCard() {
    // 使用全局key来访问Scaffold
    _scaffoldKey.currentState?.openEndDrawer();
  }
  
  // 显示导出选项对话框
  void _showExportOptions() {
    if (_questions.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有题目可导出'))
      );
      return;
    }
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择导出格式', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.description),
              title: const Text('仅导出题目', style: TextStyle(fontFamily: 'FangSong')),
              onTap: () {
                Navigator.pop(context);
                _exportToWord(WordExportType.questionsOnly);
              },
            ),
            ListTile(
              leading: const Icon(Icons.question_answer),
              title: const Text('导出题目、答案和解析', style: TextStyle(fontFamily: 'FangSong')),
              onTap: () {
                Navigator.pop(context);
                _exportToWord(WordExportType.questionsWithAnswers);
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
          ),
        ],
      ),
    );
  }
  
  // 导出题目到Word
  Future<void> _exportToWord(WordExportType exportType) async {
    try {
      // 显示加载指示器
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );
      
      // 导出题目
      final filePath = await WordExportUtil.exportQuestionsToWord(
        _questions,
        exportType: exportType,
      );
      
      // 关闭加载指示器
      Navigator.pop(context);
      
      // 显示成功消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('导出成功: $filePath'))
      );
    } catch (e) {
      // 关闭加载指示器
      Navigator.pop(context);
      
      // 显示错误消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('导出失败: $e'))
      );
    }
  }
  
  // 构建答题卡内容
  Widget _buildAnswerCardContent() {
    return SafeArea(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题栏
          Container(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
            color: Theme.of(context).primaryColor,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '答题卡',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'FangSong',
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close, color: Colors.white),
                  onPressed: () => Navigator.of(context).pop(),
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
              ],
            ),
          ),
          
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 答题统计信息
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      _buildStatCard(
                        '已答题',
                        '${_userAnswers.length}/${_questions.length}',
                        Colors.blue,
                      ),
                      _buildStatCard(
                        '正确',
                        '${_correctStatus.values.where((isCorrect) => isCorrect).length}',
                        Colors.green,
                      ),
                      _buildStatCard(
                        '错误',
                        '${_correctStatus.values.where((isCorrect) => !isCorrect).length}',
                        Colors.red,
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  
                  // 答题卡网格
                  Expanded(
                    child: SingleChildScrollView(
                      child: Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children: List.generate(_questions.length, (index) {
                          final bool isAnswered = _userAnswers.containsKey(index);
                          final bool? isCorrect = isAnswered ? _correctStatus[index] : null;
                          final bool isCurrent = index == _currentIndex;
                          
                          return InkWell(
                             onTap: () {
                               // 关闭抽屉
                               Navigator.of(context).pop();
                               setState(() {
                                 _currentIndex = index;
                                 if (isAnswered) {
                                   _selectedOption = _userAnswers[index];
                                   _isCorrect = _correctStatus[index];
                                   _showAnswer = true;
                                 } else {
                                   _selectedOption = null;
                                   _isCorrect = null;
                                   _showAnswer = false;
                                 }
                               });
                            },
                            child: Container(
                              width: 40,
                              height: 40,
                              decoration: BoxDecoration(
                                color: isAnswered
                                    ? (isCorrect! ? Colors.green : Colors.red)
                                    : (isCurrent ? Colors.blue : Colors.grey[300]),
                                border: Border.all(
                                  color: isCurrent ? Colors.blue[700]! : Colors.grey[600]!,
                                  width: isCurrent ? 2 : 1,
                                ),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Center(
                                child: Text(
                                  '${index + 1}',
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: isAnswered || isCurrent ? Colors.white : Colors.black87,
                                    fontFamily: 'FangSong',
                                  ),
                                ),
                              ),
                            ),
                          );
                        }),
                      ),
                    ),
                  ),
                  
                  const SizedBox(height: 16),
                  // 图例说明
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildLegendItem('未答', Colors.grey[300]!),
                      const SizedBox(width: 12),
                      _buildLegendItem('当前题', Colors.blue),
                      const SizedBox(width: 12),
                      _buildLegendItem('答对', Colors.green),
                      const SizedBox(width: 12),
                      _buildLegendItem('答错', Colors.red),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  // 构建统计卡片
  Widget _buildStatCard(String title, String value, Color color) {
    return Column(
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey[600],
            fontFamily: 'FangSong',
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: color,
            fontFamily: 'FangSong',
          ),
        ),
      ],
    );
  }
  
  // 构建图例项
  Widget _buildLegendItem(String label, Color color) {
    // 判断是否为深色背景
    bool isDarkColor = color == Colors.blue || color == Colors.green || color == Colors.red;
    
    return Row(
      children: [
        Container(
          width: 16,
          height: 16,
          decoration: BoxDecoration(
            color: color,
            border: Border.all(color: Colors.grey[600]!),
            borderRadius: BorderRadius.circular(2),
          ),
          child: isDarkColor ? const Center(
            child: Text(
              '✓',
              style: TextStyle(
                fontSize: 10,
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ) : null,
        ),
        const SizedBox(width: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.bold,
            fontFamily: 'FangSong',
          ),
        ),
      ],
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('$questionTypeTitle练习', style: const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
        centerTitle: true,
        actions: [
          // 导出按钮
          IconButton(
            icon: const Icon(Icons.file_download),
            tooltip: 'Word导出',
            onPressed: _showExportOptions,
          ),
          // 答题卡按钮
          IconButton(
            icon: const Icon(Icons.grid_view),
            tooltip: '答题卡',
            onPressed: _showAnswerCard,
          ),
        ],
      ),
      endDrawer: Drawer(
        width: MediaQuery.of(context).size.width * 0.5,
        child: _buildAnswerCardContent(),
      ),
      body: Column(
        children: [
          
          // 主体内容
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _errorMessage != null
                    ? Center(child: Text(_errorMessage!, style: const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)))
                    : _questions.isEmpty
                        ? _buildEmptyState()
                        : Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: [
                                // 进度指示器
                                Text(
                                  '${_currentIndex + 1}/${_questions.length}',
                                  style: Theme.of(context).textTheme.titleMedium?.copyWith(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                                  textAlign: TextAlign.center,
                                ),
                                const SizedBox(height: 20),
                                
                                // 题目卡片
                                Expanded(
                                  child: Card(
                                    elevation: 4,
                                    child: Padding(
                                      padding: const EdgeInsets.all(16.0),
                                      child: SingleChildScrollView(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            // 题目文本
                                            _buildOptionContent(
                                              _questions[_currentIndex].question,
                                              const TextStyle(fontSize: 16, fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                                            ),
                                            // 题目图片
                                            if (_questions[_currentIndex].questionImageUrl != null && 
                                                _questions[_currentIndex].questionImageUrl!.isNotEmpty) ...[  
                                              const SizedBox(height: 8.0),
                                              _buildImageWidget(_questions[_currentIndex].questionImageUrl!),
                                            ],
                                            const SizedBox(height: 20),
                                            
                                            // 选项按钮
                                            Column(
                                              children: [
                                                _buildOptionButton('A', _questions[_currentIndex].optionA, 
                                                  imageUrl: _questions[_currentIndex].optionAImageUrl),
                                                _buildOptionButton('B', _questions[_currentIndex].optionB, 
                                                  imageUrl: _questions[_currentIndex].optionBImageUrl),
                                                _buildOptionButton('C', _questions[_currentIndex].optionC, 
                                                  imageUrl: _questions[_currentIndex].optionCImageUrl),
                                                _buildOptionButton('D', _questions[_currentIndex].optionD, 
                                                  imageUrl: _questions[_currentIndex].optionDImageUrl),
                                              ],
                                            ),
                                            
                                            // 未选择选项时的提示
                                            if (_selectedOption == null && !_showAnswer)
                                              const Padding(
                                                padding: EdgeInsets.only(top: 16.0),
                                                child: Text(
                                                  '请选择一个选项',
                                                  style: const TextStyle(color: Colors.grey, fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                                                  textAlign: TextAlign.center,
                                                ),
                                              ),
                                            
                                            // 答案与解析
                                            if (_selectedOption != null || _showAnswer)
                                              Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  const Divider(height: 32),
                                                  
                                                  // 答案显示/隐藏按钮
                                                  if (!_showAnswer)
                                                    Center(
                                                      child: ElevatedButton(
                                                        onPressed: () {
                                                          setState(() {
                                                            _showAnswer = true;
                                                          });
                                                        },
                                                        child: const Text('查看答案和解析', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
                                                      ),
                                                    ),
                                                  
                                                  // 答案内容
                                                  if (_showAnswer)
                                                    Container(
                                                      padding: const EdgeInsets.all(12),
                                                      decoration: BoxDecoration(
                                                        color: _isCorrect == true
                                                            ? Colors.green[50]
                                                            : _isCorrect == false
                                                                ? Colors.red[50]
                                                                : Colors.blue[50],
                                                        borderRadius: BorderRadius.circular(8),
                                                      ),
                                                      child: Column(
                                                        crossAxisAlignment: CrossAxisAlignment.start,
                                                        children: [
                                                          // 正确/错误提示
                                                          if (_isCorrect != null)
                                                            Row(
                                                              children: [
                                                                Icon(
                                                                  _isCorrect!
                                                                      ? Icons.check_circle
                                                                      : Icons.cancel,
                                                                  color: _isCorrect!
                                                                      ? Colors.green
                                                                      : Colors.red,
                                                                ),
                                                                const SizedBox(width: 8),
                                                                Text(
                                                                  _isCorrect! ? '回答正确' : '回答错误',
                                                                  style: TextStyle(color: _isCorrect!
                                                                        ? Colors.green
                                                                        : Colors.red,
                                                                    fontWeight: FontWeight.bold,
                                                                    fontFamily: 'FangSong',
                                                                  ),
                                                                ),
                                                              ],
                                                            ),
                                                          if (_isCorrect != null)
                                                            const SizedBox(height: 12),
                                                          
                                                          // 正确答案
                                                          Row(
                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                    children: [
                                                      const Text(
                                                        '正确答案: ',
                                                        style: TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                                                      ),
                                                      Expanded(
                                                        child: _buildOptionContent(
                                                          _getCorrectAnswerText(_questions[_currentIndex]),
                                                          const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                          const SizedBox(height: 12),
                                                          
                                                          // 解析
                                                          const Text(
                                                            '解析:',
                                                            style: TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                                                          ),
                                                          const SizedBox(height: 4),
                                                          _buildOptionContent(_questions[_currentIndex].explanation, const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
                                                          // 解析图片
                                                          if (_questions[_currentIndex].explanationImageUrl != null && 
                                                              _questions[_currentIndex].explanationImageUrl!.isNotEmpty) ...[  
                                                            const SizedBox(height: 8.0),
                                                            _buildImageWidget(_questions[_currentIndex].explanationImageUrl!),
                                                          ],
                                                        ],
                                                      ),
                                                    ),
                                                ],
                                              ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                
                                // 底部按钮区域
                                Padding(
                                  padding: const EdgeInsets.only(top: 16.0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      ElevatedButton(
                                        onPressed: _currentIndex > 0 ? _previousQuestion : null,
                                        child: const Text('上一题', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
                                      ),
                                      ElevatedButton(
                                        onPressed: _currentIndex < _questions.length - 1 ? _nextQuestion : null,
                                        child: const Text('下一题', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
          ),
        ],
      ),
    );
  }
  
  // 构建图片显示组件
  Widget _buildImageWidget(String? imagePath) {
    // 如果图片路径为空，则不显示图片
    if (imagePath == null || imagePath.isEmpty) {
      return const SizedBox.shrink();
    }
    
    // 检查是否是本地文件路径
    bool isLocalFilePath = imagePath.startsWith('/') || 
                          RegExp(r'^[A-Za-z]:\\').hasMatch(imagePath) || 
                          imagePath.startsWith('c:/') || 
                          imagePath.startsWith('C:/') ||
                          imagePath.contains(':\\Users\\') ||
                          imagePath.contains(':/Users/') ||
                          imagePath.contains('/Users/') ||
                          imagePath.contains('/Documents/');
    
    if (isLocalFilePath) {
      // 在Web平台上，本地文件路径无法直接访问
      if (kIsWeb) {
        return Container(
          padding: const EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.orange.shade300),
            borderRadius: BorderRadius.circular(8.0),
            color: Colors.orange.shade50,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.warning_amber_rounded, color: Colors.orange.shade700),
                  const SizedBox(width: 8),
                  Text(
                    '本地图片无法显示',
                    style: TextStyle(color: Colors.orange.shade700, fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                '路径: $imagePath',
                style: TextStyle(fontSize: 12, color: Colors.orange.shade700, fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        );
      } else {
        // 在非Web平台上，使用File加载本地图片
        return Image.file(
          File(imagePath),
          fit: BoxFit.contain,
          height: 150,
          errorBuilder: (context, error, stackTrace) => Container(
            padding: const EdgeInsets.all(8.0),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.red.shade300),
              borderRadius: BorderRadius.circular(8.0),
              color: Colors.red.shade50,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.error_outline, color: Colors.red.shade700),
                    const SizedBox(width: 8),
                    Text(
                      '图片加载失败',
                      style: TextStyle(color: Colors.red, fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  '错误: $error',
                  style: TextStyle(fontSize: 12, color: Colors.red.shade700, fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
        );
      }
    }
    
    // 使用StatefulBuilder来管理重新加载状态
    return StatefulBuilder(
      builder: (context, setState) {
        bool isReloading = false;
        
        return Container(
          constraints: const BoxConstraints(
            maxHeight: 150, // 限制图片最大高度
          ),
          margin: const EdgeInsets.symmetric(vertical: 8.0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: Image.network(
              isReloading ? "$imagePath?reload=${DateTime.now().millisecondsSinceEpoch}" : imagePath,
              fit: BoxFit.contain,
              loadingBuilder: (context, child, loadingProgress) {
                if (loadingProgress == null) return child;
                return Container(
                  height: 80,
                  alignment: Alignment.center,
                  child: const CircularProgressIndicator(),
                );
              },
              errorBuilder: (context, error, stackTrace) {
                // 图片加载失败时显示错误信息和重试按钮
                return Container(
                  padding: const EdgeInsets.all(8.0),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.red.shade300),
                    borderRadius: BorderRadius.circular(8.0),
                    color: Colors.red.shade50,
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.error_outline, color: Colors.red.shade700),
                          const SizedBox(width: 8),
                          Text(
                            '图片加载失败',
                            style: TextStyle(color: Colors.red, fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      // 显示错误详情
                      Text(
                        '错误: ${error.toString()}',
                        style: TextStyle(fontSize: 12, color: Colors.red.shade700, fontFamily: 'FangSong', fontWeight: FontWeight.bold),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 8),
                      // 重试按钮
                      ElevatedButton.icon(
                        onPressed: () {
                          setState(() {
                            isReloading = true;
                          });
                        },
                        icon: const Icon(Icons.refresh),
                        label: const Text('重试', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.red.shade100,
                          foregroundColor: Colors.red.shade700,
                        ),
                      ),
                    ],
                  ),
                );
              },
              // 图片配置
            ),
          ),
        );
      },
    );
  }
  
  // 构建选项按钮
  Widget _buildOptionButton(String option, String content, {String? imageUrl}) {
    final bool isSelected = _selectedOption == option;
    final bool isCorrect = option == _questions[_currentIndex].correctAnswer;
    final bool showCorrectness = _showAnswer || (_selectedOption != null && isSelected);
    
    // 确定按钮颜色
    Color? backgroundColor;
    Color? textColor;
    
    if (showCorrectness) {
      if (isCorrect) {
        backgroundColor = Colors.green[100];
        textColor = Colors.green[800];
      } else if (isSelected) {
        backgroundColor = Colors.red[100];
        textColor = Colors.red[800];
      }
    } else if (isSelected) {
      backgroundColor = Colors.blue[100];
      textColor = Colors.blue[800];
    }
    
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: InkWell(
        onTap: () => _selectOption(option),
        borderRadius: BorderRadius.circular(8),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: backgroundColor ?? Colors.grey[200],
            borderRadius: BorderRadius.circular(8),
            border: Border.all(
              color: isSelected ? (isCorrect ? Colors.green : Colors.red) : Colors.grey[300]!,
              width: isSelected ? 2 : 1,
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 28,
                    height: 28,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: isSelected ? (showCorrectness ? (isCorrect ? Colors.green : Colors.red) : Colors.blue) : Colors.white,
                      border: Border.all(color: Colors.grey),
                    ),
                    child: Center(
                      child: Text(
                        option,
                        style: TextStyle(
                          color: isSelected ? Colors.white : Colors.black,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'FangSong',
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: _buildOptionContent(content, TextStyle(
                      color: textColor ?? Colors.black87,
                      fontWeight: FontWeight.bold,
                      fontFamily: 'FangSong',
                    )),
                  ),
                  if (showCorrectness) ...[  
                    Icon(
                      isCorrect ? Icons.check_circle : Icons.cancel,
                      color: isCorrect ? Colors.green : Colors.red,
                    ),
                  ],
                ],
              ),
              // 显示选项图片
              if (imageUrl != null && imageUrl.isNotEmpty) ...[  
                const SizedBox(height: 8.0),
                _buildImageWidget(imageUrl),
              ],
            ],
          ),
        ),
      ),
    );
  }
  
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.book,
            size: 80,
            color: Colors.grey,
          ),
          const SizedBox(height: 20),
          Text(
            '${questionTypeTitle}练习',
            style: Theme.of(context).textTheme.headlineMedium?.copyWith(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 40),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Text(
              '暂无${questionTypeTitle}，请先添加题目。',
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 16, fontFamily: 'FangSong', fontWeight: FontWeight.bold),
            ),
          ),
        ],
      ),
    );
  }
}

  // 构建选项内容，处理分数表达式
  Widget _buildOptionContent(String content, TextStyle style) {
    return MathFormulaWidget(
      content: content,
      style: style,
    );
  }

  // 获取正确答案文本
  String _getCorrectAnswerText(Question question) {
    String correctOption = question.correctAnswer;
    String correctText = '';
    
    switch(correctOption) {
      case 'A':
        correctText = question.optionA;
        break;
      case 'B':
        correctText = question.optionB;
        break;
      case 'C':
        correctText = question.optionC;
        break;
      case 'D':
        correctText = question.optionD;
        break;
      default:
        correctText = '未知';
    }
    
    return correctText; // 只返回选项内容，不包含选项标识
  }